<?php

namespace App\Http\Controllers\Api\V5;

use App\Common\Curl;
use App\Common\Jpush;
use App\Http\Controllers\Controller;
use App\Jobs\LiveViewChange;
use App\Jobs\StoreMsg;
use App\Models\V1\LiveGiftListModels;
use App\Models\V1\LiveLinkManageModel;
use App\Models\V1\LiveModel;
use App\Models\V1\LiveMsgModel;
use App\Models\V5\MemberModel;
use App\Module\EntMemberDRP;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;

class LiveController extends Controller
{
    protected $pre_num = 15;

    /**
     * 直播详情
     * 1.将所有的在线人数通知给所有的用户
     * 2.将刚上线的用户通知给所有人
     *
     * */
    public function live_detail(Request $request)
    {

        $key    = $request->input('key');
        $mobile = $request->input('mobile');
        $liveId = $request->input('liveId', 0);

        if (!$liveId) {
            return response()->json(['code' => 406, 'message' => '缺少直播的ID', 'data' => []]);
        }

        //判断用户是否是登录
        if (!$mobile) {
            return response()->json(['code' => 404, 'message' => '缺少手机号', 'data' => []]);
        } elseif (!$key) {
            return response()->json(['code' => 404, 'message' => '缺少设备号', 'data' => []]);
        }


        $pageId = $request->input('id', 0);

        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_mobile_key($mobile, $key);

        //验证直播的所属的类型
        $live_type = LiveModel::where(['id' => $liveId])->select('live_type')->first();

        if ($memberInfo && $live_type->live_type == 1) {//学习官

            $leve = EntMemberDRP::where('MemNumber', $memberInfo->MemNumber)->first();

            if ($leve && $leve->DRPLevel != 1) {
                return response()->json(['code' => 408, 'message' => '该直播为学习官专属', 'data' => []]);
            } elseif (!$leve) {
                return response()->json(['code' => 408, 'message' => '该直播为学习官专属', 'data' => []]);
            }
        }

        $userId = $memberInfo->UserID;

        $liveModel = new LiveModel();
        $liveId    = $liveId <= 0 ? $liveModel->get_last_live_id() : $liveId;

        //更新总的进入直播的次数
        LiveModel::where('id', $liveId)->increment('viewed_times', 1);
        $liveInfo = $liveModel->get_live_detail($liveId);
        //分享的信息
        $live_link_manage = LiveLinkManageModel::where(['live_id' => $liveId, 'link_type' => 2])->orderBy('id', 'desc')->first() ?? [];
        //订阅链接信息
        $live_link_manage_share = LiveLinkManageModel::where(['live_id' => $liveId, 'link_type' => 1])->orderBy('id', 'desc')->first() ?? [];
        $adUrl  = "";
        if($liveInfo['is_show_ad'] == 1 && $live_link_manage_share)
        {
            $url = env('HOST').$live_link_manage_share->link;
            $adUrl = preg_match('/\?/',$url) ? $url : $url."?";
        }
        $liveInfo['adUrl']      = $adUrl;
        $liveInfo['face_img']   = env('HOST') . "/" . $liveInfo['face_img'];
        $liveInfo['appName']    = $liveInfo['app'];
        $liveInfo['streamName'] = $liveInfo['strem'];
        $liveInfo['time']       = strtotime($liveInfo['begin_time']) - time();
        $liveInfo['begin_time'] = strtotime($liveInfo['begin_time'] . '+3 hours');
        $liveInfo['ad_img']     = url($liveInfo['ad_img']);
        $liveInfo['is_notice']  = (int)$liveInfo['is_notice'];

        $shareInfo = [
            'title'       => $live_link_manage ? $live_link_manage->title : '',
            'groupTitle'  => $live_link_manage ? $live_link_manage->description : "",
            'description' => $live_link_manage ? $live_link_manage->description : '',
            'img'         => $live_link_manage ? url($live_link_manage->share_img) : '',
            'link'        => $live_link_manage ? env('ADMIN_HOST') . $live_link_manage->link : '',
        ];

        $delkeys = ['description', 'live_detail_view_times', 'ali_live_view_times', 'updated_at', 'deleted_at', 'is_show', 'is_show_desc', 'live_url', 'link_url', 'preview_video', 'app', 'strem'];
        unset_array_by_keys($liveInfo, $delkeys);
        $liveInfo['shareInfo'] = $shareInfo;

        unset($liveInfo['add_view_times']);
        //添加浏览日志
        $liveModel->add_viewed_log($liveId, $userId, 0);
        $identifier = $mobile;

        $live             = config('live');
        $sdkappid         = $live['SdkAppId'];
        $private_pem_path = $live['PrivateKeyPath'];
        $signature        = $live['Signature'];

        $usersig = $this->signature($signature, $private_pem_path, $sdkappid, $identifier);

        $history              = $this->getHistoryMsg($pageId, $liveInfo['chat_group_id']);
        $count                = $this->pre_num;
        $getTeacherHistoryMsg = $this->getTeacherHistoryMsg($pageId, $liveInfo['chat_group_id']);
        $gift_list            = $this->gift_list();

        $url = 'https://console.tim.qq.com/v4/group_open_http_svc/modify_group_base_info?';
        $url = $this->tim_instance($url);

        $params = [
            'GroupId' => $liveInfo['chat_group_id'],
            'Name'    => (string)$liveInfo['viewed_times']
        ];
        $this->dispatch(new LiveViewChange($url, $params));

        return apiData()
            ->set_data('userSig', $usersig)
            ->set_data('live_info', $liveInfo)
            ->set_data('per_page', $count)
            ->set_data('history', $history)
            ->set_data('live_gift', $gift_list)
            ->set_data('teacher_history', $getTeacherHistoryMsg)
            ->send(200, 'ok');
    }

    //签名
    public function signature($signature, $private_pem_path, $sdkappid, $identifier)
    {
        $file    = app_path('../zhengshu/tencent/sig');
        $command = $signature
            . ' ' . 'gen'
            . ' ' . escapeshellarg($private_pem_path)
            . ' ' . $file
            . ' ' . escapeshellarg($sdkappid)
            . ' ' . escapeshellarg($identifier);

        $ret = exec($command, $out, $status);
        if ($status == -1) {
            return null;
        }
        $sig = file_get_contents(app_path('../zhengshu/tencent/sig'));

        return $sig;
    }

    //初始化腾讯api
    public function tim_instance($url)
    {
        $live             = config('live');
        $sdkappid         = $live['SdkAppId'];
        $identifier       = $live['Identifier'];
        $private_pem_path = $live['PrivateKeyPath'];
        $signature        = $live['Signature'];
        $contenttype      = 'json';
        $random           = 9999999;

        $usersig = $this->signature($signature, $private_pem_path, $sdkappid, $identifier);

        $params = [
            'usersig'     => $usersig,
            'identifier'  => $identifier,
            'sdkappid'    => $sdkappid,
            'random'      => $random,
            'contenttype' => $contenttype
        ];
        $url    = $url . http_build_query($params);

        return $url;
    }

    public function test()
    {
        $live             = config('live');
        $sdkappid         = $live['SdkAppId'];
        $identifier       = $live['Identifier'];
        $private_pem_path = $live['PrivateKeyPath'];
        $signature        = $live['Signature'];

        require app_path("Libs/Tencent/TimRestApi.php");

        $api = createRestAPI();

        $api->init($sdkappid, $identifier);

        //生成签名

        $ret = $api->generate_user_sig($identifier, 36000, $private_pem_path, $signature);

        $data = $api->group_get_appid_group_list();

        $GroupId = $data['GroupIdList'][0]['GroupId'];

        $data = $api->group_get_group_member_info($GroupId, 20, 1);

        foreach ($data['MemberList'] as $k => $v) {
            $ret = $api->group_send_group_msg($v['Member_Account'], $GroupId, "hello");
        }

        dd($data);
        if ($ret == null) {
            return '失败了';
        }

    }

    public function callback(Request $request)
    {
        $data = $request->all();


        if ($data['MsgBody'][0]['MsgContent']['Text']) {
            $live      = config('live');
            $user_name = $data['From_Account'];
//            Redis::set('live_info', $data['MsgBody'][0]['MsgContent']['Text']);
            $user_info = MemberModel::where(['UserName' => $user_name, 'DeleteMark' => 1])->select('YourName as user_name', 'FilePath1 as avg')->first();

            $user_name = $user_info->user_name;
            if ($data['From_Account'] === $live['Identifier']) {
                $is_teacher = true;
            } else {
                $is_teacher = false;
            }
            $avg  = $user_info->avg;
            $body = json_encode($data);
            $data = [
                'user_name'  => $user_name,
                'avg'        => $avg,
                'body'       => $body,
                'account'    => $data['From_Account'],
                'is_teacher' => $is_teacher,
                'msg'        => emoji_text_encode($data['MsgBody'][0]['MsgContent']['Text']),
                'group_id'   => $data['GroupId'],
                'msg_seq'    => $data['MsgSeq']
            ];
            Redis::set('live_info', json_encode($data));
            $store_msg = new StoreMsg($data);
            dispatch($store_msg);
            $data = [
                "ActionStatus" => "OK",
                "ErrorInfo"    => "",
                "ErrorCode"    => 0
            ];

        }

        return response()->json($data, 200);
    }

    public function get()
    {
        $data      = json_decode(Redis::get('live_msg'), true);
        $user_name = $data['From_Account'];
        $user_info = MemberModel::where(['UserName' => $user_name, 'DeleteMark' => 1])->select('YourName as user_name', 'FilePath1 as avg')->first();
        $user_name = $user_info->user_name;
        $live      = config('live');
        dd($user_name);
        if ($user_name === $live['Identifier']) {
            $is_teacher = true;
        } else {
            $is_teacher = false;
        }

        dd($is_teacher);
    }

    //获取历史信息
    public function getHistoryMsg($pageId, $chat_group_id, $page_num = 0)
    {
        $tmp      = [];
        $start_id = $page_num ? $pageId - ($page_num * ($this->pre_num)) : false;
        if ($start_id) {
            $data = LiveMsgModel::where(['is_teacher' => 0, 'group_id' => $chat_group_id])->skip($page_num * ($this->pre_num))->orderBy('created_at', 'desc')->limit($this->pre_num)->get()->toArray();
            $data = array_reverse($data);
//            dd($data);
        } else {
            $data = LiveMsgModel::where(['is_teacher' => 0, 'group_id' => $chat_group_id])->orderBy('created_at', 'desc')->limit($this->pre_num)->get()->toArray();
            $data = array_reverse($data);
        }
        foreach ($data as $k => &$v) {
//            if ($v['msg']) {
            $body                    = json_decode($v['body'], true);
            $tmp[$k]['id']           = $v['id'];
            $tmp[$k]['from_account'] = $body['From_Account'];
            $tmp[$k]['group_id']     = $v['group_id'];
            $tmp[$k]['MsgTime']      = $body['MsgTime'];
            $tmp[$k]['user_name']    = $v['user_name'];
            $tmp[$k]['avg']          = $v['avg'];
            $tmp[$k]['created_at']   = $v['created_at'];
            $tmp[$k]['updated_at']   = $v['updated_at'];
            $tmp[$k]['msg']          = emoji_text_decode($v['msg']);
//            }
        }

        return array_values($tmp);
    }

    public function getTeacherHistoryMsg($pageId, $chat_group_id)
    {
        $tmp      = [];
        $start_id = $pageId ? $pageId : false;
        if ($start_id) {
            $data = LiveMsgModel::where(['is_teacher' => 1, 'group_id' => $chat_group_id])->where('created_at', '<', $start_id)->orderBy('id', 'desc')->get()->toArray();
            $data = array_reverse($data);
        } else {
            $data = LiveMsgModel::where(['is_teacher' => 1, 'group_id' => $chat_group_id])->orderBy('created_at', 'desc')->get()->toArray();
            $data = array_reverse($data);
        }
        foreach ($data as $k => &$v) {
            $body                    = json_decode($v['body'], true);
            $tmp[$k]['id']           = $v['id'];
            $tmp[$k]['from_account'] = $body['From_Account'];
            $tmp[$k]['group_id']     = $v['group_id'];
            $tmp[$k]['MsgTime']      = $body['MsgTime'];
            $tmp[$k]['user_name']    = $v['user_name'];
            $tmp[$k]['avg']          = $v['avg'];
            $tmp[$k]['created_at']   = $v['created_at'];
            $tmp[$k]['updated_at']   = $v['updated_at'];

//            if (json_decode($v['msg'], true)['type'] === 2 && json_decode($v['msg'], true)['type'] != null) {//图片
//                $img = json_decode($v['msg'], true)['content'];
//
//                $imginfo = explode(' ', getimagesize($img)[3]);
//            } else {
//                $imginfo = ['width' => 0, 'height' => 0];
//            }
//            if (json_decode($v['msg'], true) != null) {
//                $old = json_decode($v['msg'], true);
//                array_push($old, $imginfo);
//            }


            $tmp[$k]['msg'] = json_decode($v['msg'], true);
//            $tmp[$k]['msg'] = $old;

        }

        return $tmp;
    }

    public function history(Request $request)
    {
        $pageId        = $request->input('pageId');
        $chat_group_id = $request->input('chat_group_id');
        $page_num      = $request->input('page_num', 0);
        $student       = $this->getHistoryMsg($pageId, $chat_group_id, $page_num);
        $count         = $this->pre_num;
//        $teacher       = $this->getTeacherHistoryMsg($pageId = 0, $chat_group_id);

//        return response()->json(['status' => 200, 'message' => 'ok', 'data' => ['student' => $student, 'teacher' => $teacher]], 200);
        return response()->json(['code' => 200, 'message' => 'ok', 'data' => ['per_page' => $count, 'student' => $student]], 200);
    }

    public function TimUsers()
    {
        $live             = config('live');
        $sdkappid         = $live['SdkAppId'];
        $identifier       = $live['Identifier'];
        $private_pem_path = $live['PrivateKeyPath'];
        $signature        = $live['Signature'];

        require app_path("Libs/Tencent/TimRestApi.php");

        $api = createRestAPI();

        $api->init($sdkappid, $identifier);

        //生成签名

        $ret = $api->generate_user_sig($identifier, 36000, $private_pem_path, $signature);

        $data = $api->group_get_appid_group_list();

        $GroupId = $data['GroupIdList'][0]['GroupId'];

        $data = $api->group_get_group_member_info($GroupId, 20, 1);

        return $data;
    }

    public function unicode_hanzi($str)
    {
        $str = json_decode($str, true);

        $content        = preg_replace("#\\\u([0-9a-f]{4})#ie", "iconv('UCS-2BE', 'UTF-8', pack('H4', '\\1'))", $str['content']);
        $str['content'] = $content;

        return json_encode($str);

    }

    public function cs()
    {
        dd(Redis::get('live_info'));
    }

    public function storeMsgSon($data)
    {
        Redis::set('datacc', 6666666);
        $data = LiveMsgModel::create([
            'user_name'  => $data['user_name'],
            'body'       => $data['body'],
            'avg'        => change_member_head_img($data['avg']),
            'account'    => $data['account'],
            'is_teacher' => $data['is_teacher'],
            'msg'        => $data['msg'],
            'group_id'   => $data['group_id']
        ]);
        Redis::set('data', $data);
    }

    //礼物
    public function gift_list()
    {
        $data = LiveGiftListModels::select('id', 'name', 'price', 'img_url')->get();
        foreach ($data as $k => $v) {
            $v->img_url = url($v->img_url);
            $v->price   = (double)$v->price;
        }

        return $data;
    }
}
